package com.zhongshengnetwork.rightbe.lang.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.ShareDialog;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.SignDataModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.res.Configs;
import com.zhongshengnetwork.rightbe.login.LoginActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.zhongshengnetwork.rightbe.MainActivity.REQUEST_PERMISSION;
import static com.zhongshengnetwork.rightbe.MainActivity.REQ_PERM_EXTERNAL_STORAGE;

public class SignShareActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private TopBarView topbar;
    private RelativeLayout share_layout;
    private ImageView header;
    private TextView name;

    private int screenWidth = 0;
    private int count = 0;

    private SignDataModel signDataModel = null;

    private void calculateImageWidth(){
        int width = ScreenUtils.getScreenWidth(SignShareActivity.this);
        screenWidth = width-ScreenUtils.dip2px(SignShareActivity.this, 30);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        calculateImageWidth();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
        if (requestCode == Constants.REQUEST_API) {
            if (resultCode == Constants.REQUEST_QQ_SHARE || resultCode == Constants.REQUEST_QZONE_SHARE || resultCode == Constants.REQUEST_OLD_SHARE) {
                Tencent.handleResultData(data, mIUiListener);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        signDataModel =  (SignDataModel) getIntent().getSerializableExtra("model");
        calculateImageWidth();

        setContentView(R.layout.activity_sign_share);

        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.getRightView().setImageResource(R.drawable.more);
        topbar.getRightView().setClickable(true);
        topbar.getRightView().setVisibility(View.VISIBLE);
        topbar.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                more(v);
            }
        });
        topbar.setClickListener(this);

        share_layout = (RelativeLayout) findViewById(R.id.share_layout);

        ImageView cover = (ImageView) findViewById(R.id.cover);
        ViewGroup.LayoutParams params = cover.getLayoutParams();
        params.width = screenWidth;
        params.height = Math.round(screenWidth / Configs.Value.COVER_WIDTH_HEIGHT_RATIO);
        cover.setLayoutParams(params);
        if (!CommonUtils.isEmpty(signDataModel.getImg())){
            try{
                Glide.with(SignShareActivity.this).load(signDataModel.getImg()).
                        diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(cover);
            }catch (Exception e){
                LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
            }
        }else {
            try{
                Glide.with(SignShareActivity.this).load(CustomApplication.loginModel.getBackground()).
                        diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(cover);
            }catch (Exception e){
                LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
            }
        }

        header = (ImageView) findViewById(R.id.header);
        Glide.with(SignShareActivity.this).load(CustomApplication.loginModel.getHeader()).transform(new CircleTransform(SignShareActivity.this)).dontAnimate().into(header);
        name = (TextView) findViewById(R.id.name);
        name.setText(CustomApplication.loginModel.getNickname());

        TextView sign_count = (TextView) findViewById(R.id.sign_count);
        sign_count.setText(""+signDataModel.getAll());

        TextView finish_count = (TextView) findViewById(R.id.finish_count);
        finish_count.setText(""+signDataModel.getFinish());

        TextView distance_count = (TextView) findViewById(R.id.distance_count);
        distance_count.setText(""+signDataModel.getDistance());

        TextView tip = (TextView) findViewById(R.id.tip);
        tip.setText(signDataModel.getText());

        showShare();

    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        finish();
        //Toast.makeText(LangDetailActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();

    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void more(View view){
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(SignShareActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }

        PermissionUtils.isPictureNote(SignShareActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                        if (ContextCompat.checkSelfPermission(SignShareActivity.this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                            ActivityCompat.requestPermissions(SignShareActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                                    REQUEST_PERMISSION);
                            return;
                        }
                    }else if (ActivityCompat.checkSelfPermission(SignShareActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        // 申请权限
                        ActivityCompat.requestPermissions(SignShareActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_PERM_EXTERNAL_STORAGE);
                        return;
                    }

                    final List<String> menu = new ArrayList<String>();
                    menu.add("保存");
                    menu.add("分享");
                    if (header.getVisibility() == View.VISIBLE){
                        menu.add("隐藏头像昵称");
                    }else {
                        menu.add("显示头像昵称");
                    }
                    ActionSheetDialog actionSheetDialog = new ActionSheetDialog(SignShareActivity.this)
                            .builder()
                            .setTitle("")
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true);
                    for (String m : menu){
                        actionSheetDialog.addSheetItem(m, null, new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (which == 1){
                                    final Bitmap bitmap = viewConversionBitmap(share_layout);
                                    if (bitmap != null){
                                        CommonUtils.saveBmp2Gallery(bitmap, System.currentTimeMillis()+"");
                                    }
                                }else if (which == 2){
                        /*
                        final Bitmap bitmap = viewConversionBitmap(share_layout);
                        if (bitmap != null){
                            shareBitmap = bitmap;
                            filePath = CommonUtils.getSaveBmp2Gallery(bitmap,System.currentTimeMillis()+"");
                        }
                        */
                                    showShare();
                                }else if (which == 3){
                                    if (header.getVisibility() == View.VISIBLE){
                                        header.setVisibility(View.INVISIBLE);
                                        name.setVisibility(View.INVISIBLE);
                                    }else {
                                        header.setVisibility(View.VISIBLE);
                                        name.setVisibility(View.VISIBLE);
                                    }
                                }
                            }
                        });
                    }
                    actionSheetDialog.show();
                }
            }
        });

    }

    private static Bitmap viewConversionBitmap(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Log.e("TAG", "width: " + w + " height: " + h);
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        //如果不设置canvas画布为白色，则生成透明

        //v.layout(v.getLeft(), v.getTop(), w, h);
        v.draw(c);

        return bmp;
    }


    //文件存储根目录
    private String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }
        return context.getFilesDir().getAbsolutePath();
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    //以下是分享相关的
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
    //分享文字到微信
    private void shareToWX(int type, String title){

        final Bitmap b = viewConversionBitmap(share_layout);
        if (b == null){
            return;
        }

        final Bitmap bitmap = CommonUtils.getZoomImage(b,2048);//官方说最大10M，实际达不到，为了保险起见，限制2M

        WXImageObject imgObj = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        msg.description = CommonUtils.formatString(title);
        msg.title = CommonUtils.formatString(title);
        //设置缩略图
        Bitmap thumbBmp = CommonUtils.getZoomImage(bitmap,24);//最大32k
        bitmap.recycle();
        msg.thumbData = CommonUtils.bitmapToBytes(thumbBmp);//Util.bmpToByteArray(thumbBmp, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        req.scene = type==0 ? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
        CustomApplication.mWxApi.sendReq(req);

    }

    private MyIUiListener mIUiListener = new MyIUiListener();
    class MyIUiListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            //Log.e("TAG","分享成功");
            uploadShareResult();
        }

        @Override
        public void onError(UiError uiError) {
            Log.e("TAG","分享出错");
        }

        @Override
        public void onCancel() {
            Log.e("TAG","分享取消");
        }

        @Override
        public void onWarning(int i) {

        }
    }

    //分享到qq
    private Bundle params;
    private void shareToQQ(int type,String title){
        final Bitmap b = viewConversionBitmap(share_layout);
        if (b == null){
            return;
        }

        final Bitmap bitmap = CommonUtils.getZoomImage(b,2048);//官方说最大10M，实际达不到，为了保险起见，限制2M

        String localPath = CommonUtils.getSaveBmp2Gallery(bitmap, System.currentTimeMillis()+"");
        params = new Bundle();
        if (type == 0){//分享给QQ好友

            if (!CommonUtils.isEmpty(localPath)){
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
                //params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
                //params.putString(QQShare.SHARE_TO_QQ_SUMMARY, title);// 摘要
                //params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,AppShareUrl);// 内容地址LangShareUrl+langInfoModel.getLangid()
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, localPath);
                params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "");//其它附加功能
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CustomApplication.mTencent.shareToQQ(SignShareActivity.this, params, mIUiListener);
                        //CommonUtils.deleteFileByPath(localPath);
                    }
                });
            }

        }else if(type == 1){
            //分享到QQ空间
            if (!CommonUtils.isEmpty(localPath)){

                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
                //params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
                //params.putString(QQShare.SHARE_TO_QQ_SUMMARY, title);// 摘要
                //params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,AppShareUrl);// 内容地址LangShareUrl+langInfoModel.getLangid()
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, localPath);
                params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);//其它附加功能
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CustomApplication.mTencent.shareToQQ(SignShareActivity.this, params, mIUiListener);
                        //CommonUtils.deleteFileByPath(localPath);
                    }
                });


            }
        }
    }

    private void showShare(){
        final ShareDialog shareDialog = new ShareDialog(SignShareActivity.this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        shareDialog.friend_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //分享到朋友圈
                shareToWX(0, signDataModel.getText());

            }
        });
        shareDialog.wx_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //分享给微信好友
                shareToWX(1, signDataModel.getText());

            }
        });
        shareDialog.wb_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                final Bitmap b = viewConversionBitmap(share_layout);
                if (b == null){
                    return;
                }

                final Bitmap bitmap = CommonUtils.getZoomImage(b,2048);//官方说最大10M，实际达不到，为了保险起见，限制2M
                if (bitmap != null){
                    CustomApplication.WbShareType = 1;
                    CustomApplication.WbShareSourceId = CommonUtils.getUUID();
                    CustomApplication.WbShareText = signDataModel.getText();
                    CustomApplication.wbHasImage = true;
                    CustomApplication.wbShareBitmap = bitmap;
                    Intent mIntent = new Intent(BroadcastDefine.WeiBo_Share_Action);
                    //发送广播
                    sendBroadcast(mIntent);
                }
            }
        });
        shareDialog.qq_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //分享到qq
                shareToQQ(0, signDataModel.getText());

            }
        });
        shareDialog.zone_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //qq空间
                shareToQQ(1, signDataModel.getText());

            }
        });
        shareDialog.show();
    }

    private void uploadShareResult(){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("id", CommonUtils.getUUID());
        map.put("type","11");
        String url = "miniapp/"+"langappid"+"/sharelanginfo.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(final String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            count += 1;
                        }else {
                            CustomApplication.showTip(commonModel, SignShareActivity.this);
                        }
                    }
                });
            }

            @Override
            public void onError(String msg) {

            }
        });
    }
    
}
